import Router from "koa-router";
import jsdom from "jsdom";
import httpRequest from "@/utils/http";
import { Result } from "@/utils/result";

const essayRouter = new Router({ prefix: "/api/daily/essay" });

essayRouter.get("/", async (ctx, next) => {
    // const {data: htmlStr} = await axios.get("https://meiriyiwen.com/")
    // const { data: htmlStr } = await axios.get("https://meiriyiwen.com/random/iphone");
    // const { data: htmlStr } = await axios.get("https://www.dushu.com/meiwen/random/");
    const htmlStr = await httpRequest.get({
        baseURL: "https://www.dushu.com/meiwen/random/"
    });

    // 解析字符串为 dom，并获取 document 对象
    const { JSDOM } = jsdom;
    const { document } = new JSDOM(htmlStr).window;

    // pc(已固定为滕王阁序，遂放弃)
    // const title = document.querySelector('title')?.textContent.split(' ')[0]
    // const author = document.querySelector('.article_author')?.textContent

    // phone (https://meiriyiwen.com/) 已经失效
    // const title = document.querySelector(".articleTitle").textContent;
    // const author = document.querySelector(".articleAuthorName").textContent;

    // 解析每日一读dom
    const title = document.querySelector(`h1[style="text-align:center;"]`).textContent;
    const author = document.querySelector(`.article-info > span[style="margin:0;padding:0;"]`)?.textContent;
    // 获取 NodeList 类数组
    // const pNodeList = document.querySelectorAll('#article_show .article_text p')
    const pNodeList = document.querySelectorAll(`.text p`);
    const content = [...pNodeList].map(item => item.textContent);
    console.log(title);

    Result.ok(ctx, { title, author, content }, "文章获取成功");
    // ctx.body = {
    //     code: 200,
    //     data: { title, author, content }
    // };
});

export default essayRouter;
